package com.sf.message.service;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dm.model.v20151123.SingleSendMailRequest;
import com.aliyuncs.dm.model.v20151123.SingleSendMailResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.gson.JsonObject;
import com.sf.message.domain.VerificationCodeVO;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
 * Description:
 * Date: 2018-07-14
 * @author purui_zhang
 * Time: 17:14
 */
@Slf4j
public class CurrencyMessageService {
    private String product;
    private String domain;
    private String accessKeyId;
    private String accessKeySecret;
    private String signName;
    private String templateCode;
    private Integer initialCapacity;
    private Integer concurrencyLevel;
    private Integer expire;

    private String jpushAppKey;
    private String jpushMasterSecret;

    private String accountName;
    private String fromAlias;

    private Cache<String, String> cache;

    public CurrencyMessageService(String product, String domain, String accessKeyId, String accessKeySecret,
                                  String signName, String templateCode, Integer initialCapacity, Integer concurrencyLevel,
                                  Integer expire, String jpushAppKey, String jpushMasterSecret,
                                  String accountName, String fromAlias) {
        this.product = product;
        this.domain = domain;
        this.accessKeyId = accessKeyId;
        this.accessKeySecret = accessKeySecret;
        this.signName = signName;
        this.templateCode = templateCode;
        this.initialCapacity = initialCapacity;
        this.concurrencyLevel = concurrencyLevel;
        this.expire = expire;
        this.jpushAppKey = jpushAppKey;
        this.jpushMasterSecret = jpushMasterSecret;
        this.accountName = accountName;
        this.fromAlias = fromAlias;
    }

    @PostConstruct
    private void initCache(){
        cache = CacheBuilder.newBuilder()
                // 设置cache的初始大小为10，要合理设置该值
                .initialCapacity(initialCapacity)
                // 设置并发数为5，即同一时间最多只能有5个线程往cache执行写入操作
                .concurrencyLevel(concurrencyLevel)
                // 设置cache中的数据在写入之后的存活时间为30分钟
                .expireAfterWrite(expire, TimeUnit.MINUTES)
                // 构建cache实例
                .build();
    }

    /**
     *  发送验证码
     * @param verificationCodeVO
     * @param signName
     * @return
     * @throws Exception
     */
    public String getMobileVerificationCode(VerificationCodeVO verificationCodeVO,String signName) throws Exception {
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        SendSmsRequest request = new SendSmsRequest();
        request.setMethod(MethodType.POST);
        request.setPhoneNumbers("00" + verificationCodeVO.getMobileDistrict() + verificationCodeVO.getMobile());
        request.setSignName(signName);
        request.setTemplateCode(templateCode);
        int checkCode = (int)((Math.random() * 9 + 1) * 100000);
        request.setTemplateParam("{\"checkCode\":\"" + checkCode + "\"}");
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        log.info("阿里云短信发送响应:{}",sendSmsResponse.getMessage());
        if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK"))
        {
            cache.put(verificationCodeVO.getMobile() + verificationCodeVO.getBusinessType(), checkCode + "");
            return "checkCode";
        }
        else
        {
            throw new Exception("验证码发送失败！");
        }
    }
    /**
     *  发送验证码
     * @param verificationCodeVO
     * @param signName
     * @return
     * @throws Exception
     */
    public String getMobileVerificationCode(String code,VerificationCodeVO verificationCodeVO,String signName) throws Exception {
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        SendSmsRequest request = new SendSmsRequest();
        request.setMethod(MethodType.POST);
        request.setPhoneNumbers("00" + verificationCodeVO.getMobileDistrict() + verificationCodeVO.getMobile());
        request.setSignName(signName);
        request.setTemplateCode(templateCode);
        int checkCode = (int)((Math.random() * 9 + 1) * 100000);
        JSONObject jsonObject= new JSONObject();
        jsonObject.put(code,checkCode);
        request.setTemplateParam(jsonObject.toJSONString());
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        log.info("阿里云短信发送响应:{}",sendSmsResponse.getMessage());
        if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK"))
        {
            cache.put(verificationCodeVO.getMobile() + verificationCodeVO.getBusinessType(), checkCode + "");
            return "checkCode";
        }
        else
        {
            throw new Exception("验证码发送失败！");
        }
    }
    /**
     *  发送通知
     * @param verificationCodeVO
     * @param signName
     * @return
     * @throws Exception
     */
    public String sendMessage(String templateParam,VerificationCodeVO verificationCodeVO,String signName,String templateCode) throws Exception {
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        SendSmsRequest request = new SendSmsRequest();
        request.setMethod(MethodType.POST);
        request.setPhoneNumbers("00" + verificationCodeVO.getMobileDistrict() + verificationCodeVO.getMobile());
        request.setSignName(signName);
        request.setTemplateCode(templateCode);
        request.setTemplateParam(templateParam);
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        log.info("阿里云短信发送响应:{}",sendSmsResponse.getMessage());
        if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK"))
        {
            return "checkCode";
        }
        else
        {
            throw new Exception("验证码发送失败！");
        }
    }
    /**
     *  验证验证码
     * @param verificationCodeVO
     * @return
     */
    public boolean matchingMobileVerificationCode(VerificationCodeVO verificationCodeVO){
        String code = cache.getIfPresent(verificationCodeVO.getMobile() + verificationCodeVO.getBusinessType());
        if (null==code)
        {
            // 手机号码未验证或验证码超时
            log.warn("手机号码未验证或验证码超时:{},输入验证码为:{}",verificationCodeVO.getMobile(),verificationCodeVO.getVerificationCode());
            return false;
        }
        if (code.equals(verificationCodeVO.getVerificationCode())){
            log.info("验证码验证成功:{}",verificationCodeVO.getMobile());
            return true;
        }
        else {
            log.warn("验证码输入错误:{}",verificationCodeVO.getMobile());
            // 验证码输入错误
            return false;
        }
    }

    /**
     *  阿里云 简单邮件 推送
     * @return
     */
    public SingleSendMailResponse singleSendEmail(int addressType,String tagName,boolean replyToAddress,String toAddress,String subject,String body){
        log.info("简单邮件发送 邮件标签:{},使用回信地址{},收件人地址:{},邮件标题:{},邮件内容:{}",tagName,replyToAddress,toAddress,subject,body);
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        SingleSendMailRequest request = new SingleSendMailRequest();
        try {
            request.setAccountName(accountName);
            request.setFromAlias(fromAlias);
            request.setAddressType(addressType);
            request.setTagName(tagName);
            request.setReplyToAddress(replyToAddress);
            request.setToAddress(toAddress);
            request.setSubject(subject);
            request.setHtmlBody(body);
            SingleSendMailResponse httpResponse = client.getAcsResponse(request);
            log.info("阿里云 简单邮件 推送 响应:{}",httpResponse.getRequestId());
            return httpResponse;
        } catch (Exception e) {
            log.error("阿里云 简单邮件 推送 出错:{}",e.getMessage());
        }
        return null;
    }
    /**
     *  阿里云 批量邮件 推送(使用模板)
     * @return
     */
//    public BatchSendMailResponse batchSendEmail(int addressType, String tagName, boolean replyToAddress, String toAddress, String subject, String body){
//        log.info("批量邮件发送 邮件标签:{},使用回信地址{},收件人地址:{},邮件标题:{},邮件内容:{}",tagName,replyToAddress,toAddress,subject,body);
//        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
//        IAcsClient client = new DefaultAcsClient(profile);
//        BatchSendMailRequest request = new BatchSendMailRequest();
//        try {
//            request.setAccountName(accountName);
//            request.setAddressType(addressType);
//            request.setReceiversName();
//            request.setTagName(tagName);
//            request.setTemplateName("注册");
//
//            BatchSendMailResponse acsResponse = client.getAcsResponse(request);
//            return acsResponse;
//        } catch (Exception e) {
//            log.error("阿里云 批量邮件 推送 出错:{}",e.getMessage());
//        }
//        return null;
//    }

    /**
     *  极光推送 android
     * @param parm
     * @return
     */
    public PushResult sendAndroidMessage(Map<String, String> parm){
        //创建JPushClient(极光推送的实例)
        JPushClient jpushClient = new JPushClient(jpushMasterSecret, jpushAppKey);
        //推送的关键,构造一个payload
        PushPayload payload = PushPayload.newBuilder()
                //指定android平台的用户
                .setPlatform(Platform.android())
                //你项目中的所有用户
                .setAudience(Audience.all())
                .setNotification(Notification.android(parm.get("msg"), parm.get("title"), parm))
                //发送内容,这里不要盲目复制粘贴,这里是我从controller层中拿过来的参数)
                .setOptions(Options.newBuilder().setApnsProduction(false).build())
                //这里是指定开发环境,不用设置也没关系 //自定义信息
                .setMessage(Message.content(parm.get("msg")))
                .build();
        try {
            PushResult pu = jpushClient.sendPush(payload);
            return pu;
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     *  极光推送 android and IOS
     * @param parm
     * @return
     */
    public PushResult sendAndroidAndIosMessage(Map<String, String> parm){
        //创建JPushClient(极光推送的实例)
        JPushClient jpushClient = new JPushClient(jpushMasterSecret, jpushAppKey);
        //推送的关键,构造一个payload
        PushPayload payload = PushPayload.newBuilder()
                //指定android 和 IOS 平台的用户
                .setPlatform(Platform.android_ios())
                //你项目中的所有用户
                .setAudience(Audience.all())
                .setNotification(Notification.android(parm.get("msg"), parm.get("title"), parm))
                //发送内容,这里不要盲目复制粘贴,这里是我从controller层中拿过来的参数)
                .setOptions(Options.newBuilder().setApnsProduction(false).build())
                //这里是指定开发环境,不用设置也没关系 //自定义信息
                .setMessage(Message.content(parm.get("msg")))
                .build();
        try {
            PushResult pu = jpushClient.sendPush(payload);
            return pu;
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     *  极光推送 IOS
     * @param parm
     * @return
     */
    public PushResult sendIOSMessage(Map<String, String> parm){
        //创建JPushClient(极光推送的实例)
        JPushClient jpushClient = new JPushClient(jpushMasterSecret, jpushAppKey);
        //推送的关键,构造一个payload
        PushPayload payload = PushPayload.newBuilder()
                //指定android平台的用户
                .setPlatform(Platform.ios())
                //你项目中的所有用户
                .setAudience(Audience.all())
                .setNotification(Notification.android(parm.get("msg"), parm.get("title"), parm))
                //发送内容,这里不要盲目复制粘贴,这里是我从controller层中拿过来的参数)
                .setOptions(Options.newBuilder().setApnsProduction(false).build())
                //这里是指定开发环境,不用设置也没关系 //自定义信息
                .setMessage(Message.content(parm.get("msg")))
                .build();
        try {
            PushResult pu = jpushClient.sendPush(payload);
            return pu;
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *  极光推送 指定用户推送 注册id
     * @param parm
     * @return
     */
    public PushResult sendToUserByRegId(Map<String, String> parm){
        //创建JPushClient(极光推送的实例)
        JPushClient jpushClient = new JPushClient(jpushMasterSecret, jpushAppKey);
        String registionId = parm.get("registionId");
        //推送的关键,构造一个payload
        PushPayload payload = PushPayload.newBuilder()
                //指定的用户
                .setPlatform(Platform.android_ios())
                //你项目中的所有用户
                .setAudience(Audience.registrationId(registionId))
                .setNotification(Notification.android(parm.get("msg"), parm.get("title"), parm))
                //发送内容,这里不要盲目复制粘贴,这里是我从controller层中拿过来的参数)
                .setOptions(Options.newBuilder().setApnsProduction(false).build())
                //这里是指定开发环境,不用设置也没关系 //自定义信息
                .setMessage(Message.content(parm.get("msg")))
                .build();
        try {
            PushResult pu = jpushClient.sendPush(payload);
            return pu;
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *  极光推送 指定用户推送 别名
     * @param parm
     * @return
     */
    public PushResult sendToUserByAlias(Map<String, String> parm){
        //创建JPushClient(极光推送的实例)
        JPushClient jpushClient = new JPushClient(jpushMasterSecret, jpushAppKey);
        String alias = parm.get("alias");
        //推送的关键,构造一个payload
        PushPayload payload = PushPayload.newBuilder()
                //指定的用户
                .setPlatform(Platform.android_ios())
                //你项目中的所有用户
                .setAudience(Audience.alias(alias))
                .setNotification(Notification.android(parm.get("msg"), parm.get("title"), parm))
                //发送内容,这里不要盲目复制粘贴,这里是我从controller层中拿过来的参数)
                .setOptions(Options.newBuilder().setApnsProduction(false).build())
                //这里是指定开发环境,不用设置也没关系 //自定义信息
                .setMessage(Message.content(parm.get("msg")))
                .build();
        try {
            PushResult pu = jpushClient.sendPush(payload);
            return pu;
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
        return null;
    }
}
